package com.miao.util.zip;

import com.google.common.io.Closer;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by miao on 2015/4/10.
 */
public class ZipUtils {
    public static void main(String[] args) {
        ZipUtils book = new ZipUtils();
        try {
            book.zip("D:\\test.zip", new File("f:\\test"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void zip(String zipFileName, File inputFile) throws Exception {
        System.out.println("压缩中...");
        Closer closer = Closer.create();
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFileName));
            closer.register(out);
            bo = new BufferedOutputStream(out);
            closer.register(bo);
            zip(out, inputFile, inputFile.getName(), bo);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            closer.close();
        }
        System.out.println("压缩完成");
    }

    public void zip(OutputStream outputStream, File inputFile) throws Exception {
        System.out.println("压缩中...");
        Closer closer = Closer.create();
        ZipOutputStream out = null;
        BufferedOutputStream bo = null;
        try {
            out = new ZipOutputStream(outputStream);
            closer.register(out);
            bo = new BufferedOutputStream(out);
            closer.register(bo);
            zip(out, inputFile, inputFile.getName(), bo);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            closer.close();
        }
        System.out.println("压缩完成");
    }

    private void zip(ZipOutputStream out, File f, String base, BufferedOutputStream bo) throws Exception {
        if ((f == null) || (!f.exists())) {
            return;
        }
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            if (fl.length == 0) {
                out.putNextEntry(new ZipEntry(base + "/"));
                System.out.println(base + "/");
            }
            for (int i = 0; i < fl.length; i++)
                zip(out, fl[i], base + "/" + fl[i].getName(), bo);
        } else {
            out.putNextEntry(new ZipEntry(base));
            System.out.println(base);
            FileInputStream in = null;
            BufferedInputStream bi = null;
            Closer closer = Closer.create();
            try {
                in = new FileInputStream(f);
                bi = new BufferedInputStream(in);
                byte[] b = new byte[8192];
                while (bi.read(b) != -1)
                    bo.write(b);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                closer.close();
            }
        }
    }
}
